package com.lzgcoding.onlineshopapp.feature.main.cart

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lzgcoding.onlineshopapp.room.dao.ItemDao
import com.lzgcoding.onlineshopapp.room.entity.ItemEntity
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update

class CartViewModel(
    private val itemDao: ItemDao
) : ViewModel() {
    private val _uiState = MutableStateFlow(CartUIState())
    val uiState = _uiState.onStart {
        initData()
    }.stateIn(
        viewModelScope,
        SharingStarted.WhileSubscribed(5000),
        _uiState.value
    )

    private suspend fun initData() {
        val items = itemDao.getAll().mapIndexed { index, entity ->
            Pair(entity, (index % 4).coerceIn(1, 3))
        }
        _uiState.update { state ->
            val subtotal = items.sumOf { it.first.price * it.second }
            state.copy(
                items = items,
                subtotal = subtotal,
                total = subtotal + state.totalTax + state.freeDelivery
            )
        }
    }

    fun increase(entity: ItemEntity) {
        _uiState.update { state ->
            val newItems = state.items.map {
                if (it.first.id == entity.id) {
                    Pair(entity, it.second + 1)
                } else {
                    it
                }
            }
            val subtotal = newItems.sumOf { it.first.price * it.second }
            state.copy(
                items = newItems,
                subtotal = subtotal,
                total = subtotal + state.totalTax + state.freeDelivery
            )
        }
    }

    fun decrease(entity: ItemEntity) {
        _uiState.update { state ->
            val newItems = state.items.map {
                if (it.first.id == entity.id) {
                    Pair(entity, (it.second - 1).coerceAtLeast(0))
                } else {
                    it
                }
            }.toMutableList().apply {
                removeAll { it.second == 0 }
            }
            val subtotal = newItems.sumOf { it.first.price * it.second }
            state.copy(
                items = newItems,
                subtotal = subtotal,
                total = subtotal + state.totalTax + state.freeDelivery
            )
        }
    }

    fun onSearchValueChange(value: String) {
        _uiState.update { it.copy(searchValue = value) }
    }
}